import { useAtom, useAtomValue } from 'jotai'
import { chatsAtom, currentChatIdAtom } from '@/atoms'
import { MessageType } from '@/types'

export default function useMessage() {
  const [chats, setChats] = useAtom(chatsAtom)
  const currentChatId = useAtomValue(currentChatIdAtom)

  const insertMessage = (message: MessageType) => {
    setChats(chats.map((chat) => {
      if (chat.id == currentChatId) {
        chat.messages = [...chat.messages, message]
      }
      return { ...chat }
    }))
  }

  const deleteMessage = (id: string) => {
    setChats(chats.map((chat) => {
      if (chat.id == currentChatId) {
        const index = chat.messages.findIndex(item => item.id == id)
        chat.messages.splice(index, 1)
      }
      return { ...chat }
    }))
  }

  const sliceMessage = (id: string) => {
    setChats(chats.map((chat) => {
      if (chat.id == currentChatId) {
        const index = chat.messages.findIndex(item => item.id == id)
        chat.messages = chat.messages.slice(0, index + 1)
      }
      return { ...chat }
    }))
  }

  const updateMessage = (message: MessageType) => {
    message.timestamp = new Date().getTime()
    const handle = (msgs: MessageType[]) => {
      return msgs.map((m) => {
        if (m.id === message.id) {
          return { ...message }
        }
        return m
      })
    }
    setChats(chats.map((chat) => {
      if (chat.id != currentChatId)
        return chat
      chat.messages = handle(chat.messages)
      return { ...chat }
    }))
  }

  return {
    insertMessage,
    deleteMessage,
    sliceMessage,
    updateMessage,
  }
}
